package us.gaaoc.framework.webapp.backingbeans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;

import us.gaaoc.framework.manager.RoleManager;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.Organizations;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.PersonOrganizations;
import us.gaaoc.framework.model.Profile;
import us.gaaoc.framework.model.Roles;
import us.gaaoc.framework.model.Signatures;
import us.gaaoc.framework.webapp.backingbeans.profile.Menu;

/**
 * This class decides the authorized user. 
 * @author Sukahda Tapshalkar
 * Sep 6, 2006
 *
 */
@SuppressWarnings({"unchecked", "unused"})
public class ClientPage extends BaseBackingBean{
	
	/**
	 * properties
	 */
	/** Default Serial Version UID */
	private static final long serialVersionUID = 1L;
	private String firstName;
	private String lastName;
	private String username;
	private String password;
	private String password2;
	private String emailAddress;
	private String sigTrackingId;
	private Signatures sig;
	private Person personSigner;
	private static final Logger LOG = Logger.getLogger(ClientPage.class);
	private String build;
	private String version;
	
	public void setBuild(String build) {
		this.build = build;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	public String getBuild() {
		return build;
	}
	public String getVersion() {
		return version;
	}
	
	
	
	boolean jsfManaged;
	
	/**
	 * 
	 * Constructor
	 *
	 */
	public ClientPage() {
		jsfManaged = true;
	}
	
	public ClientPage(HttpSession httpSession)
	{
		jsfManaged = false;
		session = httpSession;
	}
	
	HttpSession session;
	
	public HttpSession sessionMap()
	{
		if(jsfManaged)
		{
			return (HttpSession) this.getFacesContext().getExternalContext().getSession(true);
		}
		return session;
	}
	

	public String login_Masq(String courtUuid)
	{
		Person person = this.getModelFacade().login(this.username, this.password);

		String succesString = "";
		Menu menu = null;
		Court court = null;
		
		if (person == null) {
			this.getFacesContext().addMessage("clientForm", new FacesMessage(
					"Invalid User"));
			return "failure";

		} else {
			if(person.getOrganizations().size() == 0){
				this.getFacesContext().addMessage("clientForm", new FacesMessage("User cannot login. There is no court associated with the user."));
				return null;
			} else {

				court = this.getModelFacade().findCourtByUuid(courtUuid);
				sessionMap().setAttribute("courtName", court.getName());
				System.out.println("court id is: " + courtUuid);
				
				List<Roles> personRoles = person.getRoles();

				RoleManager roleManager = new RoleManager(true);
				menu = roleManager.manageTabForUser(court.getName(),personRoles);

				for (Roles r : personRoles) {
					if (r.getRole().contains("admin")) {
						succesString = "adminDashboard";											
						sessionMap().setAttribute("role",r);
						break;
					} else if (r.getRole().contains("clerk")) {
						sessionMap().setAttribute("role",r);
						succesString = "clerkDashboard";
					} else if (r.getRole().equals("public")) {
						sessionMap().setAttribute("role",r);
						succesString = "publicDashboard";
					} else if (r.getRole().equals("agent")) {
						sessionMap().setAttribute("role",r);
						succesString = "agentDashboard";
					} else if (r.getRole().equals("attorney")) {
						sessionMap().setAttribute("role",r);
						succesString = "attorneyDashboard";
					} else if (r.getRole().contains("judge")) {
						sessionMap().setAttribute("role",r);
						succesString = "judgeDashboard";
						break;
					}
				}
			}
			
			List<Organizations> personOrgs = new ArrayList<Organizations>();
			for(PersonOrganizations o : person.getOrganizations()){
				Hibernate.initialize(o.getOrganization());
				personOrgs.add(o.getOrganization());
			}
			
			sessionMap().setAttribute("menu", menu);
			sessionMap().setAttribute("person",person);
			sessionMap().setAttribute("court",court);
			sessionMap().setAttribute("personOrgs", personOrgs);
			//this.getFacesContext().getExternalContext().getSessionMap().put("courtUuid",courtUuid);			
			return succesString;
		}
	}
	
	/**
	 * This method checks the person which trying to login is authorized or not.
	 * If the person is not authorized then again login page will be displayed.
	 * @return String
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public String login() throws ServletException, IOException {

        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        
        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                 .getRequestDispatcher("/j_spring_security_check");
 
        dispatcher.forward((ServletRequest) context.getRequest(),
                (ServletResponse) context.getResponse());
 
        FacesContext.getCurrentInstance().responseComplete();
        // It's OK to return null here because Faces is just going to exit.
        return null;
	}

	/**
	 * This method navigates user to the forgot password page.
	 * @return String
	 */
	public String forgotPassword() {
		return "forgotPasswordPage";
	}

	/**
	 * This method navigates user to the forgot user id page.
	 * @return String
	 */
	public String forgotUserId() {
		return "toForgotUserIdPage";
	}

	/**
	 * This method sends user userId and the corresponding password by email.
	 * @return
	 * @throws Exception
	 */
	public String sendUserPasswordByMail() throws Exception {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Person person = this.getModelFacade().getPersonByUserName(this.username);
		if (person == null) {
			facesContext.addMessage("forgotPasswordForm", new FacesMessage(
					"User Does not Exist in the Database"));
			return "failuerUserIdMessagePage";

		} else {
			Profile personProfile = person.getProfile();

			String password = person.getPassword();
			String email = personProfile.getEmail();
			System.out.println("email of the person "+email);
			String subject = " Here is your password";

			String message = "Forgotten Password: "
					+ "\n"
					+ "Here are your requested information for http://localhost:8080/GAJE_BibbCounty_1.0/client.faces"
					+ "\n" + "User Name: " + person.getUserId() + "\n"
					+ "Password: " + password;
			/*
			 * for (Roles r : personRoles) { if (r.getRole().contains("admin")) {
			 * succesString = "adminDashboard"; break; }
			 * 
			 * else if (r.getRole().contains("clerk")) { succesString =
			 * "clerkDashboard"; } else if (r.getRole().equals("public")) {
			 * succesString = "publicDashboard"; }
			 */
			//EmailController emailController = new EmailController();
			//emailController.send(email, "admin@gaaoc.us", subject, message);
			/*
			 * Add the Email Controller stuff here
			 */
			return "successUserIdMessagePage";
		}

	}

	/**
	 * This method sends UserID to the user by email.
	 * @return String
	 * @throws Exception
	 */
	public String sendUserIdByMail() throws Exception {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Profile profile = this.getModelFacade().getPersonProfileByEmail(this.getEmailAddress());
		
		if (profile == null){
			facesContext.addMessage("forgotPasswordForm", new FacesMessage(
			"User Does not Exist in the Database"));
			return "failuerEmailMessagePage";	
		}else {
			Person person = profile.getPerson();
			
			String pUserId = person.getUserId();
			String password = person.getPassword();
			
			String subject = " Here is your password";

			String message = "Forgotten Password: "
					+ "\n"
					+ "Here are your requested information for http://localhost:8080/GAJE_BibbCounty_1.0/client.faces"
					+ "\n" + "User Name: " + pUserId + "\n"
					+ "Password: " + password;
//			EmailController emailController = new EmailController();
	//		emailController.send(this.getEmailAddress(), "admin@gaaoc.us", subject, message);
			return "successEmailMessagePage";
		}
	}

	/**
	 * This method navigates user to the Login Page
	 * @return
	 */
	public String gotoLoginPage() {
		return "toLogInPage";
	}

	/**
	 * @return Returns the password.
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            The password to set.
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return Returns the username.
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            The username to set.
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return emailAddress
	 */
	public String getEmailAddress() {
		return emailAddress;
	}

	/**
	 *  The emailAddress to set
	 * @param emailAddress
	 */
	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	/**
	 * Setter for property firstName
	 * @return firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * Getter for property firstName
	 * @param firstName
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * Getter for property lastName
	 * @return lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * Setter for property lastName
	 * @param lastName
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * Getter for property password2
	 * @return password2
	 */
	public String getPassword2() {
		return password2;
	}

	/**
	 * Setter for property password2
	 * @param password2
	 */
	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getSigTrackingId() {
		return sigTrackingId;
	}

	public void setSigTrackingId(String sigTrackingId) {
		this.sigTrackingId = sigTrackingId;
	}
	
	
	public String sigDetails(){		
		
		if(this.sigTrackingId.equalsIgnoreCase("")){
			this.getFacesContext().addMessage("sigForm:sigTrackingIdSubmit",
					new FacesMessage(
							"Please enter a valid signature tracking id. "));
			return "failure";
		}
		Signatures signature = this.getModelFacade().findSignatureFromSignatureTrackingID(this.sigTrackingId);
		if (signature == null) {
			this.getFacesContext().addMessage("sigForm:sigTrackingIdSubmit",
					new FacesMessage(
							"Please enter a valid signature tracking id. "));

			return null;
		} else {
			LOG.info("The signature's uuid is .." + signature.getUuid());
			this.sig = signature;
			LOG.info("The signature's uuid is .." + sig.getUuid());
			LOG.info("The person that signed is .."
					+ sig.getSignedByPerson().getFirstName() + " "
					+ sig.getSignedByPerson().getLastName());
			//Person person = this.modelFacade.findPersonById(sig.getSignedByPerson().getUuid());
			//Person person = this.getModelFacade().findPersonById(sig.getSignedByPerson().getUuid());
			//this.personSigner = person;
			this.personSigner = sig.getSignedByPerson();
			LOG.info("The person signed is .."+this.personSigner.getFirstName()+" "+this.personSigner.getLastName());
			return "viewSignatureDetails";
			/*this.personSigner = sig.getSignedByPerson();
			LOG.info("The person signed is .."+this.personSigner.getFirstName()+" "+this.personSigner.getLastName());
			return "viewSignatureDetails"; */
		}
	}

	public Signatures getSig() {
		return sig;
	}

	public void setSig(Signatures sig) {
		this.sig = sig;
	}

	public Person getPersonSigner() {
		return personSigner;
	}

	public void setPersonSigner(Person personSigner) {
		this.personSigner = personSigner;
	}

}